package com.jpsl.core.items;


import com.jpsl.core.util.Assert;
import com.jpsl.core.util.Pair;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 处理 if 分支
 *
 * @param <E>
 * @author 懒王猫
 */
class Branches<E> {

    private final List<Pair<Condition, Supplier<E>>> list = new ArrayList<>(4);

    Branches<E> add(Condition condition, Supplier<E> supplier) {
        Assert.notNull(condition, "condition");
        Assert.notNull(supplier, "supplier");
        list.add(Pair.of(condition, supplier));
        return this;
    }

    /**
     * <p>前面的分支条件匹配后, 后面的分支条件不再去看;</p>
     * <p>类似于 if () elseIf () elseIf() else ...</p>
     * @return
     */
    E getItem() {
        for (Pair<Condition, Supplier<E>> branch : list) {
            if (branch.getLeft().test()) {
                return branch.getRight().get();
            }
        }
        return null;
    }

}